package com.kc.sjwh.service;

import java.util.List;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kc.sjwh.dao.RoleDao;
import com.kc.sjwh.dao.UserDao;
import com.kc.sjwh.entity.bo.UserBo;
import com.kc.sjwh.entity.po.Role;
import com.kc.sjwh.entity.po.User;
import com.kc.sjwh.other.Cfg;
import com.kc.sjwh.other.MyToken;
import com.kc.sjwh.other.QueryParam;

/**
 * 自定义认证与授权的实现
 * date: 2017年5月16日
 * @author zhangGuihua(hua7381@163.com)
 */
@Service
public class MyRealm extends AuthorizingRealm {
	@Autowired
	UserDao userDao;
	@Autowired
	RoleDao roleDao;

	/**
	 * 获取认证（登录）
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken t) throws AuthenticationException {
		MyToken token = (MyToken)t;
		
		String acc = token.getUsername();
		String pwd = new String(token.getPassword());
		User user = null;

		//验证
		if("admin".equals(acc) && Cfg.getInst().getAdminPwd().equals(pwd)) {
			user = new UserBo();
			user.setId("admin");
			user.setMc("管理员");
			
		} else {
			user = userDao.getOne("get", new QueryParam().put("zh", acc));
			if(user == null) {
				throw new AccountException("用户不存在");
			}
			pwd = new Md5Hash(pwd).toString();
			if(!pwd.equals(user.getMm())) {
				throw new AccountException("密码错误");
			}
			
			List<Role> roles = roleDao.getListByAppAndUser(user.getId(), Cfg.getInst().getAppCode());
			if(roles.size() == 0) {
				throw new AccountException("抱歉，没有给您分配该系统的使用权限");
			}
		}
		
		
		//验证成功
		token.setUser(user);
		
		return new SimpleAuthenticationInfo(token, token.getPassword(), token.getUsername());
	}
	
	/**
	 * 获取权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {
		System.out.println("---AuthorizationInfo()");
		//根据token确定当前登陆者
		MyToken token = (MyToken)p.getPrimaryPrincipal();
		User u = token.getUser();
		
		//根据 userId 查出 roles 和 permissions，若只根据roles控制权限，则permissions可略
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		List<Role> roles = roleDao.getListByAppAndUser(u.getId(), Cfg.getInst().getAppCode());
		
		for(Role r : roles) {
			info.addRole(r.getDm());
		}
		
		if(u.getId().equals("admin")) {//虚拟管理员
			info.addRole("admin");
		}
		
//		info.addStringPermission("update");
//		info.addStringPermission("user:delete");
		
		return info;
	}

}
